import axios from 'axios'

const API_PREFIX = import.meta?.env?.VITE_API_PREFIX || ''

export async function fetchAreas() {
  if (API_PREFIX) {
    const res = await axios.get(`${API_PREFIX}/register/areas`)
    return res.data
  }
  return [
    { id: 'a1', name: '四川省保健院南苑', address: '四川省成都市锦江区画溪路666号' },
    { id: 'a2', name: '四川省保健院北苑', address: '四川省成都市锦江区画溪路666号' },
    { id: 'a3', name: '四川省保健院体检中心', address: '四川省成都市锦江区画溪路666号' }
  ]
}

export async function fetchDepartments({ areaId } = {}) {
  if (API_PREFIX) {
    const res = await axios.get(`${API_PREFIX}/register/departments`, { params: { areaId } })
    return res.data
  }
  const common = [
    { id: 'd1', name: '内科', children: [ { id: 'd1-1', name: '心内科' }, { id: 'd1-2', name: '消化内科' } ] },
    { id: 'd2', name: '外科', children: [ { id: 'd2-1', name: '骨科' }, { id: 'd2-2', name: '普外科' } ] },
    { id: 'd3', name: '儿科', children: [ { id: 'd3-1', name: '小儿内科' } ] },
    { id: 'd4', name: '妇产科', children: [ { id: 'd4-1', name: '产科' } ] }
  ]
  if (areaId === 'a3') {
    return common.filter(d => d.id !== 'd2') // 体检中心无外科
  }
  return common
}

export async function searchDoctors({ keyword = '', deptId, areaId } = {}) {
  if (API_PREFIX) {
    const res = await axios.get(`${API_PREFIX}/register/doctors`, { params: { keyword, deptId, areaId } })
    return res.data
  }
  const all = [
    { id: 'u1', name: '张伟', title: '主任医师', avatar: '🧑‍⚕️', deptId: 'd1-1', deptName: '心内科', fee: 30, supportIM: true, schedule: '今日下午, 明日上午', remain: 5, areaId: 'a1' },
    { id: 'u2', name: '李静', title: '副主任医师', avatar: '👩‍⚕️', deptId: 'd1-2', deptName: '消化内科', fee: 25, supportIM: false, schedule: '明日全天', remain: 0, areaId: 'a1' },
    { id: 'u3', name: '王磊', title: '主治医师', avatar: '🧑‍⚕️', deptId: 'd2-1', deptName: '骨科', fee: 20, supportIM: true, schedule: '今日上午', remain: 8, areaId: 'a2' },
    { id: 'u4', name: '赵敏', title: '主治医师', avatar: '👩‍⚕️', deptId: 'd3-1', deptName: '小儿内科', fee: 18, supportIM: true, schedule: '后日下午', remain: 6, areaId: 'a3' }
  ]
  return all.filter(d => (!areaId || d.areaId === areaId) && (!deptId || d.deptId === deptId) && (!keyword || d.name.includes(keyword) || d.deptName.includes(keyword)))
}

export async function fetchSlots(doctorId) {
  if (API_PREFIX) {
    const res = await axios.get(`${API_PREFIX}/register/doctors/${doctorId}/slots`)
    return res.data
  }
  const map = {
    u1: [ { id: 's1', time: '今天 14:00-14:30', remain: 2 }, { id: 's2', time: '明天 09:00-09:30', remain: 3 } ],
    u2: [ ],
    u3: [ { id: 's3', time: '今天 09:30-10:00', remain: 5 } ]
  }
  return map[doctorId] || []
}

export async function submitBooking({ doctorId, slotId }) {
  if (API_PREFIX) {
    const res = await axios.post(`${API_PREFIX}/register/book`, { doctorId, slotId })
    return res.data
  }
  const slots = await fetchSlots(doctorId)
  const slot = slots.find(s => s.id === slotId)
  if (!slot || slot.remain <= 0) {
    const err = new Error('号源已满')
    err.code = 'SOLD_OUT'
    throw err
  }
  return new Promise(resolve => setTimeout(() => resolve({ success: true, bookingId: `BKG${Date.now()}`, payAmount: 30 }), 500))
}

export function pushRecentDoctor(doctor) {
  if (!doctor) return
  try {
    const key = 'recentDoctors'
    const arr = JSON.parse(localStorage.getItem(key) || '[]')
    const filtered = [doctor, ...arr.filter(d => d.id !== doctor.id)].slice(0, 5)
    localStorage.setItem(key, JSON.stringify(filtered))
  } catch (_) {}
}

export function getRecentDoctors() {
  try {
    const arr = JSON.parse(localStorage.getItem('recentDoctors') || '[]')
    return arr
  } catch (_) { return [] }
}

export default {
  fetchAreas,
  fetchDepartments,
  searchDoctors,
  fetchSlots,
  submitBooking,
  pushRecentDoctor,
  getRecentDoctors
}


